import json
import logging
from datetime import datetime
from DrissionPage import Chromium, ChromiumOptions
from DrissionPage.common import Settings

# 设置日志
logging.basicConfig(level = logging.INFO,format = '%(asctime)s %(name)s %(levelname)s %(message)s')
logger = logging.getLogger(__name__)

# 加载配置信息
with open('douyin_fire.json', 'r', encoding='utf-8') as f:
    data = json.load(f)

# 设置报错信息中文
Settings.set_language('zh_cn')

co = ChromiumOptions()
co.incognito(True)  # 匿名模式
co.headless(True)  # 无头模式
co.mute(True) #静音
co.set_argument('--no-sandbox')  # 无沙盒模式
co.set_argument('--disable-blink-features=AutomationControlled')
co.set_argument('--window-size', '1920,1080') #窗口大小
co.set_pref('credentials_enable_service', False) # 阻止“自动保存密码”的提示气泡
co.set_argument('--hide-crash-restore-bubble') # 阻止“要恢复页面吗？Chrome未正确关闭”的提示气泡

# 遍历
for index, item in enumerate(data):
    logger.info(f"开始第{index+1}个用户，共{len(data)}个用户")
    browser = Chromium(addr_or_opts=co)
    tab = browser.latest_tab
    cookie = item.get("cookie")
    tab.set.cookies(cookie)
    tab.set.user_agent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36 Edg/137.0.0.0")

    try:
        logger.info("进入网站")
        tab.get('https://www.douyin.com/?recommend=1')
        tab.wait(1)
        try:
            logger.info("点击取消弹窗")
            tab("tx=取消").click(timeout=5)
        except Exception:
            logger.warning("没有弹窗，跳过")
        tab.wait(1)
        logger.info("进入私信")
        tab("tx=私信").click(timeout=5)

        for user in item.get("name"):
            tab.wait(1)
            logger.info(f"进入联系人：{user}")
            tab("tx="+user+"").click(timeout=5,by_js=None)
            tab.wait(1)
            logger.info("发送消息")
            tab("tx=发送消息").input(item.get("msg"))
            tab.wait(1)
            tab("@d=M12.34 16.117a1.16 1.16 0 0 0 1.64 1.64l2.395-2.394v8.838a1.16 1.16 0 0 0 2.321 0v-8.839l1.028 1.028 1.368 1.368a1.16 1.16 0 1 0 1.64-1.641l-4.219-4.22a1.382 1.382 0 0 0-1.954 0l-4.22 4.22h.001z").click(timeout=5)
            tab.wait(1)
            tab("tx=退出会话").click(timeout=5)
    except Exception as e:
        tab.wait(3)
        tab.get_screenshot(path='error', name=f"pic_{datetime.now().strftime('%Y%m%d_%H%M%S')}.jpg", full_page=True)
        logger.error(f'失败: {e}')

    tab.wait(5)
    browser.quit()